#!/bin/bash
# 使用方法   00,15,30,45 * * * * /usr/sbin/mysql_bak.sh
# 定义变量
DBHOST='127.0.0.1'
DBPORT=3306
DBUSER='root'
DBPASSWORD='123456'
DATADIR="/var/lib/mysql/"

CURDATE=$(date +%Y_%m_%d)
CURHOUR=$(date +%H)
CURMINUTE=$(date +%M)
CURSECOND=$(date +%S)

XDB="/usr/local/percona/bin/xtrabackup"
DBBAK_DIR="/db_bak/"

# 创建数据备份总目录
[ ! -d "${DBBAK_DIR}" ] && mkdir -p "${DBBAK_DIR}"

# 创建单日数据备份目录
[ ! -d "${DBBAK_DIR}/${DAY}" ] && mkdir -p "${DBBAK_DIR}/${DAY}"

# 创建单时数据备份目录
[ ! -d "${DBBAK_DIR}/${CURDATE}/${CURDATE}_${CURHOUR}" ] && mkdir -p "${DBBAK_DIR}/${CURDATE}/${CURDATE}_${CURHOUR}"


# 根据时间判断动作
BASE_DIR="${DBBAK_DIR}/${CURDATE}/${CURDATE}_${CURHOUR}/${CURDATE}_${CURHOUR}_00"
TARGET_DIR="${DBBAK_DIR}/${CURDATE}/${CURDATE}_${CURHOUR}/${CURDATE}_${CURHOUR}_${CURMINUTE}"
if [ ${CURMINUTE} == "00" ];then
        /usr/bin/echo "full"
        ${XDB} --host="${DBHOST}" --port="${DBPORT}" --user="${DBUSER}" --password="${DBPASSWORD}" --backup --datadir="${DATADIR}" --target-dir="${BASE_DIR}"
else
        /usr/bin/echo "diff"
        [ ! -d "${BASE_DIR}" ] && /usr/bin/echo "base not exists" && exit
        ${XDB} --host="${DBHOST}" --port="${DBPORT}" --user="${DBUSER}" --password="${DBPASSWORD}" --backup --datadir="${DATADIR}" --target-dir="${TARGET_DIR}" --incremental-basedir="${BASE_DIR}"
fi
